package netty.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    AtomicInteger seq = new AtomicInteger();

    public UdpClientHandler() {
        log.info(">>> init {}", this.toString());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("connect to {}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("disconnect from {}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        log.info("receive data: ", packet);

        String response = packet.content().toString(CharsetUtil.UTF_8);
        if (response.startsWith("QOTM: ")) {
            log.info("Quote of the Moment: " + response.substring(6));
            seq.incrementAndGet();
        }

        if (seq.get() >= 10) {
            ctx.channel().close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }

}
